package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.StringUtils;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdChkTask;
import com.gqj.meter.domain.vo.MdChkTaskVo;
import com.gqj.meter.service.IMdChkTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 盘点任务Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/checkTask", description = "盘点任务")
@RestController
@RequestMapping("/meter/checkTask")
public class MdChkTaskController extends BaseController {
    @Autowired
    private IMdChkTaskService mdChkTaskService;
    @Value("${downloadPath}")
    private String downloadPath;

    /**
     * 查询盘点任务列表
     */
    @ApiOperation("查询盘点任务列表")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdChkTask mdChkTask) {
        startPage();
        List<MdChkTask> list = mdChkTaskService.selectMdChkTaskList(mdChkTask);
        return getDataTable(list);
    }

    /**
     * 导出盘点任务列表
     */
    @ApiOperation("导出盘点任务列表")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:export')")
    @Log(title = "盘点任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdChkTask mdChkTask) {
        List<MdChkTask> list = mdChkTaskService.selectMdChkTaskList(mdChkTask);
        ExcelUtil<MdChkTask> util = new ExcelUtil<MdChkTask>(MdChkTask.class);
        util.exportExcel(response, list, "盘点任务数据");
    }

    /**
     * 获取盘点任务详细信息
     */
    @ApiOperation("获取盘点任务详细信息")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:query')")
    @GetMapping(value = "/{chkTaskId}")
    public AjaxResult getInfo(@PathVariable("chkTaskId") Long chkTaskId) {
        return success(mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskId));
    }

    /**
     * 新增盘点任务
     */
    @ApiOperation("新增盘点任务")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:add')")
    @Log(title = "盘点任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdChkTask mdChkTask) {
        if (StringUtils.isEmpty(mdChkTask.getAssetsCategory())) {
            return AjaxResult.error("资产大类不能为空，请检查重试");
        }
        if (StringUtils.isEmpty(mdChkTask.getCheckRange())) {
            return AjaxResult.error("盘点范围不能为空，请检查重试！");
        }
        return toAjax(mdChkTaskService.insertMdChkTask(mdChkTask));
    }

    /**
     * 修改盘点任务
     */
    @ApiOperation("修改盘点任务")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:edit')")
    @Log(title = "盘点任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdChkTask mdChkTask) {
        return toAjax(mdChkTaskService.updateMdChkTask(mdChkTask));
    }

    /**
     * 删除盘点任务
     */
    @ApiOperation("删除盘点任务")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:remove')")
    @Log(title = "盘点任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{chkTaskIds}")
    public AjaxResult remove(@PathVariable Long[] chkTaskIds) {
        return toAjax(mdChkTaskService.deleteMdChkTaskByChkTaskIds(chkTaskIds));
    }

    /**
     * 开始盘点
     */
    @ApiOperation("开始盘点")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:startCheck')")
    @GetMapping(value = "/startCheck/{chkTaskIds}")
    public AjaxResult startCheck(@PathVariable("chkTaskIds") Long[] chkTaskIds) {
        if (chkTaskIds.length == 0) {
            return AjaxResult.error("未获取到盘点单据信息，请检查重试");
        }

        for (int i = 0; i < chkTaskIds.length; i++) {
            MdChkTask mdChkTask = mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskIds[i]);
            if ("03".equals(mdChkTask.getStatusCode())) {
                return AjaxResult.error("单据" + mdChkTask.getChkTaskId() + "已经盘点结束，无法开始盘点");
            } else if ("02".equals(mdChkTask.getStatusCode())) {
                return AjaxResult.error("单据" + mdChkTask.getChkTaskId() + "盘点中，无法开始盘点");
            }
        }
        return toAjax(mdChkTaskService.startCheck(chkTaskIds));
    }

    /**
     * 下载盘点单json文件
     */
    @ApiOperation("下载盘点单json文件")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:downloadJsonMdChkTask')")
    @GetMapping("/downloadJsonMdChkTask")
    public AjaxResult downloadJsonMdChkTask(MdChkTask mdChkTask) {
        //只下载盘点开始的单据
        mdChkTask.setStatusCode("02");
        //判断是否选中的单据都是盘点开始状态
        Long[] chkTaskIds = mdChkTask.getChkTaskIds();
        for (int i = 0; i < chkTaskIds.length; i++) {
            MdChkTask chkTask = mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskIds[i]);
            if (!"02".equals(chkTask.getStatusCode())) {
                return AjaxResult.error("单据" + chkTask.getChkTaskId() + "不是开始盘点状态，请重新选择!");
            }
        }
        List<MdChkTask> pos = mdChkTaskService.selectMdChkTaskList(mdChkTask);
        List<MdChkTaskVo> vos = StorageUtil.copyList(pos, MdChkTaskVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "盘点单数据" + orderNo);
        return AjaxResult.success(fileName + "盘点单数据" + orderNo);
    }


    /**
     * 处理明细-盘点正常
     */
    @ApiOperation("处理明细-盘点正常")
    @Log(title = "处理明细-盘点正常")
    @GetMapping("checkTaskNormal/{taskDetailsIds}/{queryChkTaskId}")
    public AjaxResult checkTaskNormal(@PathVariable Long[] taskDetailsIds, @PathVariable Long queryChkTaskId) {
        return toAjax(mdChkTaskService.checkTaskNormal(taskDetailsIds, queryChkTaskId));
    }



    /**
     * 完成盘点
     */
    @ApiOperation("完成盘点")
    @PreAuthorize("@ss.hasPermi('meter:checkTask:endCheck')")
    @GetMapping(value = "/endCheck/{chkTaskIds}")
    public AjaxResult endCheck(@PathVariable("chkTaskIds") Long[] chkTaskIds) {
        if (chkTaskIds.length == 0) {
            return AjaxResult.error("未获取到盘点单据信息，请检查重试");
        }

        for (int i = 0; i < chkTaskIds.length; i++) {
            MdChkTask mdChkTask = mdChkTaskService.selectMdChkTaskByChkTaskId(chkTaskIds[i]);
            if (!"02".equals(mdChkTask.getStatusCode())) {
                return AjaxResult.error("单据" + mdChkTask.getChkTaskId() + "盘点未开始，无法结束盘点");
            }
        }
        return toAjax(mdChkTaskService.endCheck(chkTaskIds));
    }
}
